<script  setup>
import { reactive, ref, watch, watchEffect } from 'vue'

      let count = ref(10);

      function increase(){
        count.value++;
      }

      function decrease(){
        count.value--;
      }

      let carts = reactive([
        {
          name:"可乐",
          price:10,
          count:10
        },
        {
          name:"炸鸡",
          price:18,
          count:2
        },
        {
          name:"薯片",
          price:5,
          count:6
        },
      ])

      let deleteItem = function(index){
          carts.splice(index,1)
      }

      let compute = function(){
          let total = 0;
          for(let index in carts){
            total += carts[index].count*carts[index].price
          }
          return total;
      }

      let clearCarts = function(){
        carts.splice(0,carts.length)
      }

      let firstName = ref("长")

      let lastName = reactive({
        name:"话"
      })

      let fullName = ref("")

      function full(){
        fullName = firstName.value+lastName.name
        return fullName;
      }

      // watch(firstName,(newValue,oldValue)=>{
      //   fullName.value = firstName.value+lastName.name
      // })

      // watch(()=>lastName,(newvalue,oldvalue)=>{
      //   fullName.value = firstName.value+lastName.name
      // },{deep:true,immediate:true})

      watchEffect(()=>{
        fullName = firstName.value+lastName.name
      })


</script>

<template>
  <div>

    <button @click="increase()">+</button>
    <span v-text="count"></span>
    <button @click="decrease()">-</button>
    <hr>
    购物车的删除
    <table border="1px">
      <thead>
        <tr>
          <td>名称</td>
          <td>价格</td>
          <td>数量</td>
          <td>总价</td>
          <td>操作</td>
        </tr>
        
      </thead>
      <tbody v-if="carts.length>0">
        <tr  v-for="(item,index) in carts" :key="index">
          <td v-text="item.name"></td>
          <td v-text="item.price"></td>
          <td v-text="item.count"></td>
          <td v-text="item.price*item.count"></td>
          <td>
            <button @click="deleteItem(index)">删除</button>
          </td>
        </tr>
        
      </tbody>
      <tbody v-else>
        购物车空了
      </tbody>

    </table>
    <button @click="clearCarts()">一键清空购物车</button>
    <br>

    总金额为：{{ compute() }}

    <hr>

    watch案例
    <hr>
    姓：<input type="text" v-model="firstName"><br>
    名字：<input type="text" v-model="lastName.name"><br>
    全名：{{ fullName }}




  </div>


</template>

<style scoped>

</style>
